package org.trendit

class PostController {
	def scaffold = true
    //def index() { }
	def search = {
		
	}
	def embed = {}
	def pre = {}
	def status = {}
	def results = {
		def posts = Post.findAllPostTagsLike(params.tag) 
		return [ posts: posts, term : params.tag ]
	}
	
	def timeline = {
		def user = User.findByUserId(params.id)
		 [user:user]
		}
	
	def addPost = {
		def user = User.findByUserId(params.id) 
		if (user) {
			
		
		//def post = new Post("<a href="+params.content+">"+params.content+"</a>") 
		//String con = HttpHandle.getResponseText(params.content)
		//PostDetail pd = HttpHandle.parseJson(con)
		//pd.setPost(post)
		//pd.save()
		String response1 = HttpHandle.getResponseText(params.content);
		def post = HttpHandle.parseJson(response1,params.content);
		//PostDetail.add(det)
		if(post==null)
		println "post is null"
		println post.description
//		if(det.save()){
//			flash.message = "Successfully created Postdetails"
//		}
//		post.postAttr = det
		String[] tagStr = new String(params.'hidden-Atag').split(',')
		
		List<String> taglist = new ArrayList<String>()
		for(String stt:tagStr){
			if(Tag.findByName(stt)){
				taglist.add(stt)
			}else{
			   def t = new Tag(stt,user)
			   t.save()
			   taglist.add(stt)
			}
		}
		
	    post.tags = Tag.findAllByNameInList(taglist)
		user.addToPosts(post)
		if (user.save()) {
		flash.message = "Successfully created Post"
		} else {
		user.discard()
		flash.message = "Invalid or empty post" }
		}else{
		flash.message = "Invalid User Id"
		}
		redirect(action: 'timeline', id: params.id) }
}
